/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.blog.city.checkthedep.sessionbeans;

import com.blog.city.checkthedep.entities.Article;
import com.blog.city.checkthedep.entities.Category;
import com.blog.city.checkthedep.entities.Comment;
import com.blog.city.checkthedep.entities.Tag;
import java.util.LinkedList;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

/**
 *
 * @author Breath
 */
@Stateless
public class Search implements SearchLocal {

    @PersistenceContext(unitName = "com.blog.city_CheckTheDep_war_1.0-SNAPSHOTPU")
    private EntityManager em;

    /**
     * 
     * @return
     */
    public EntityManager getEntityManager() {
        return em;
    }

    /**
     * 
     * @param em
     */
    public void setEntityManager(EntityManager em) {
        this.em = em;
    }

    /**
     * 
     * @param content
     * @return
     */
    @Override
    public List<Object> searchByKeyword(String content) {
        List<Article> article = null;
        List<Tag> tags = null;
        List<Comment> comment = null;
        content = "%" + content + "%";

        if (em.createQuery("SELECT a FROM Article a WHERE a.articleBody LIKE :content").setParameter("content", content).getResultList() != null) {
            article =(List<Article>) em.createQuery("SELECT a FROM Article a WHERE a.articleBody LIKE :content").setParameter("content", content).getResultList();
        } else {
            //throw new Exception("Search in article body was not successful");
        }

        if (em.createQuery("SELECT t FROM Tag t WHERE t.name LIKE :content").setParameter("content", content).getResultList() != null) {
            tags = (List<Tag>)em.createQuery("SELECT t FROM Tag t WHERE t.name LIKE :content").setParameter("content", content).getResultList();
        } else {
            //throw new Exception("Search in category was not successful");
        }

        if (em.createQuery("SELECT co FROM Comment co WHERE co.commentBody LIKE :content").setParameter("content", content).getResultList() != null) {
            comment = (List<Comment>)em.createQuery("SELECT co FROM Comment co WHERE co.commentBody LIKE :content").setParameter("content", content).getResultList();
        } else {
            //throw new Exception("Search in comment body was not successful");
        }

        List<Object> results = new LinkedList<Object>();

        results.addAll((List<Article>)article);

        results.addAll((List<Tag>)tags);

        results.addAll((List<Comment>)comment);

        return results;
    }
}
